package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.ButtonActivity;
import com.ycsj.goldmedalnewconcept.adapter.ListViewAdapter;
import com.ycsj.goldmedalnewconcept.bean.HomeworkResponse;
import com.ycsj.goldmedalnewconcept.bean.LoginResponse;
import com.ycsj.goldmedalnewconcept.bean.StudentInfo;
import com.ycsj.goldmedalnewconcept.bean.StudentInfoResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//布置作业
@SuppressLint("HandlerLeak")
public class AssignmentActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private TextView finish;
	private TextView tv_submit;
	private TextView tv_history;
	private GridView gv_student;
	private EditText et_homework;
	private EditText et_comment;
	private String content;
	private String class_id;
	private String account;
	private String role;
	private String title;
	private String ttel;
	private String num;
	private Intent intent;
	private Handler handler;
	private Handler handler1;
	private HomeworkAdapter mAdapter;
	private List<StudentInfo> list;
	private List<StudentInfo> stulist;
	private List<StudentInfo> stulist2;
	private List<String> stulist3;
	private List<Integer> potionlist;
	private String studentids;
	private String comment;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_assignment);
		intent = getIntent();
		list = new ArrayList<StudentInfo>();
		stulist = new ArrayList<StudentInfo>();
		stulist2 = new ArrayList<StudentInfo>();
		stulist3 = new ArrayList<String>();
		potionlist = new ArrayList<Integer>();
		handler = new MyHandler();
		handler1 = new MyHandler1();
		class_id = intent.getStringExtra("class_id");
		ttel = intent.getStringExtra("ttel");
		num = intent.getStringExtra("num");
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		Log.e("test", class_id);
		initView();
		setOnListener();
		initStudent();
	}

	private void initStudent() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		// builder.add("ttel", "13006314760");
		builder.add("ttel", ttel);
		builder.add("num", num);
		builder.add("platform", "2");
		// http://192.168.0.164:8080/ycsj_count/MessageCenter?type=2&ttel=13006314760&num=1&platform=2
		// http://pm.moregolden.com/ycsj_count/MessageCenter?type=2&ttel=18672626702&num=1&platform=2
		Request request = new Request.Builder()
				// .url("http://pm.moregolden.com/ycsj_count/MessageCenter")
				.url(Constant.ycsj_count_MessageCenter).post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json1 = arg0.body().string();
				StudentInfoResponse fromJson = gson.fromJson(json1,
						StudentInfoResponse.class);
				Log.e("test", json1);

				if (fromJson != null && fromJson.list != null) {
					stulist = fromJson.list;

					for (int i = 0; i < stulist.size(); i++) {
						potionlist.add(i);
					}
					Log.e("test", "size"+potionlist.size());
				}

				Message message = Message.obtain();
				message.arg1 = 0;
				message.obj = fromJson;
				handler1.sendMessage(message);
			}
		});
	}

	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_submit = (TextView) findViewById(R.id.tv_submit);
		tv_history = (TextView) findViewById(R.id.tv_history);
		finish = (TextView) findViewById(R.id.finish);
		gv_student = (GridView) findViewById(R.id.gv_student);
		et_homework = (EditText) findViewById(R.id.et_homework);
		et_comment = (EditText) findViewById(R.id.et_comment);

	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "1");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("studentids", studentids);
	
		builder.add("title", "");
		builder.add("school", "");
		builder.add("userclass", class_id);
		builder.add("content", content);
		builder.add("comment", comment);
		builder.add("status", "0");
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				HomeworkResponse fromJson = gson.fromJson(json,
						HomeworkResponse.class);
				//
				Message message = Message.obtain();
				message.arg1 = 0;
				message.obj = fromJson;
				handler.sendMessage(message);
			}
		});
	}

	public class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			HomeworkResponse fromJson = (HomeworkResponse) msg.obj;
			if (fromJson == null) {
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
						.show();
				return;
			}

			if ("1".equals(fromJson.state)) {
				for (int i = 0; i < stulist2.size(); i++) {
					pushMsg(stulist2.get(i).sttel);
				}
				Toast.makeText(getApplicationContext(), "发布成功", 0).show();
				intent = new Intent(AssignmentActivity.this,
						HomeWorkHistoryActivity.class);
				intent.putExtra("class_id", class_id);
				startActivity(intent);
				
			} else {
				Toast.makeText(getApplicationContext(), "上传失败", 0).show();
			}
		}
	}

	// 推送
	private void pushMsg(String userid) {
		// TODO Auto-generated method stub
		OkHttpClient mOkHttpClient3 = new OkHttpClient();
		// 创建一个Request
		final Request request3 = new Request.Builder().url(
				Constant.ycsj_count_MessageCenter + "?type=32&alias=" + userid
						+ "1" + "&content=点击查看最新作业" + "&title=收到作业"
						+ "&ptype=1").build();

		// http://www.moregolden.com/ycsj_count/MessageCenter?type=32&alias=182712617791&content=提交的请假申请已批准&title=请假成功了&ptype=1
		Call call3 = mOkHttpClient3.newCall(request3);
		call3.enqueue(callback3);
	}

	Callback callback3 = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			String json = arg0.body().string();
			Log.e("jpush", json);
			handler.postDelayed(new Runnable() {

				@Override
				public void run() {

				}
			}, 0);
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};

	public class MyHandler1 extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			StudentInfoResponse fromJson = (StudentInfoResponse) msg.obj;
			if (fromJson == null) {
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
						.show();
				return;
			}

			list = fromJson.list;
			mAdapter = new HomeworkAdapter();
			gv_student.setAdapter(mAdapter);

		}
	}

	class HomeworkAdapter extends BaseAdapter {
		private LayoutInflater inflater = LayoutInflater.from(getBaseContext());

		@Override
		public int getCount() {
			if (null != list) {
				return list.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.gv_item_homework, null);
				viewHolder = new ViewHolder();
				viewHolder.title = (TextView) convertView
						.findViewById(R.id.title);
				viewHolder.tv_birthday = (TextView) convertView
						.findViewById(R.id.tv_birthday);
				viewHolder.image = (ImageView) convertView
						.findViewById(R.id.image);
				viewHolder.ck_student = (CheckBox) convertView
						.findViewById(R.id.ck_student);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
//			viewHolder.title.setText(list.get(position).nickname);
			viewHolder.tv_birthday.setText(list.get(position).name);
			Picasso.with(getBaseContext()).load(list.get(position).icon)
					.error(R.drawable.header).into(viewHolder.image);

			viewHolder.ck_student
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							int s = 1;
							for (int i = 0; i < potionlist.size(); i++) {
								if (position == potionlist.get(i)) {
									s = 2;
									potionlist.remove(i);
								}
							}
							if (s == 1) {
								potionlist.add(position);
							}
							Log.e("test", "size"+potionlist.size());
						}
					});

			return convertView;
		}
	}

	class ViewHolder {
		public TextView title;
		public ImageView image;
		public TextView tv_birthday;
		public CheckBox ck_student;
	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
		tv_history.setOnClickListener(this);
		finish.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
		case R.id.finish:
			finish();
			break;
		case R.id.tv_submit:
			// 发布
			content = et_homework.getText().toString().trim();
			comment = et_comment.getText().toString().trim();
			if (comment == null) {
				comment = "";
			}

			if ("".equals(content)) {
				Toast.makeText(this, "作业内容不能为空", Toast.LENGTH_SHORT).show();
				return;
			}


			if (potionlist.size()==0) {
				Toast.makeText(this, "请选中学生", Toast.LENGTH_SHORT).show();
				return;
			}
			
			for (int i = 0; i < potionlist.size(); i++) {
				
				stulist2.add(stulist.get(potionlist.get(i)));
			}
			
			Gson gson = new Gson();
			studentids = gson.toJson(stulist2);
			initData();
			break;
		case R.id.tv_history:
			// 历史记录
			intent = new Intent(this, HomeWorkHistoryActivity.class);
			intent.putExtra("class_id", class_id);
			startActivity(intent);

			break;
		}
	}

}
